<script>
	import {
		getAppletBinding,
		appletLogin,
		moduleVersion
	} from '@/api/index.js';
	import {
		getRequest,
		parseQueryStringt
	} from '@/static/js/common.js';
	import {
		base64decode,
		base64encode,
		utf8to16
	} from '@/static/js/Base64.js';
	import { confAllColor, confAll } from '@/api/card.js';
	import {
		currentMember
	} from '@/api/recruit.js';
	import env from '@/api/env.js';
	// #ifdef H5
	import VConsole from 'vconsole';
	// #endif
	export default {
		// 打包时需要确定文件内容 ：pages html meta
		// 全局变量 数字人datahuman 招聘resume
		// http://ebc-test.benwunet.com/resume/#/recruit/user/index?
		// 静态文件地址
		// https://ebc-prod.cdn.benwunet.com/uni-static/
		globalData: {
			createBwqDetail: {}, // 创建本无签 数据
			cueTheme: 'day-theme', // 白色
			appTheme: 'night-theme', //黑色 2:lightBlue-theme | 1: night-theme
			cardTemp: {}, // 名片信息
			vitaTemp: {}, // 简历
			recruitmentTemp: {}, // 招聘
			workExperience: {}, // 工作经历
			projectExperience: {}, // 项目经历
			companyId: '', // 公司ID
			companyInfo: {}, // 公司信息
			userId: '', // 用户ID
			filterTemp: {}, //筛选0
			hotArticleTemp: {}, // 热文预览
			statusBarHeight: 0, // 状态栏高度
			// pagesNav: [],
			loginCount: 1, // 是否登录
			loginFirst: false, // 是否第一次登录
			historyUrl: '', // 历史记录url
			homeAddress:'',
			globalColor: {
				style: '', // 通用样式配置 --
			},
			accountLogVOList:[]
		},
		onLaunch: function(option) {
			console.log('onLaunch-------', option);
			let scene = '';
			if (option.query.scene || option.query.cardId) {
				scene = option.query.scene || option.query.cardId;
			}
			// #ifdef H5
			// 测试环境打开console
			if (env.API_BASE_URL == 'http://ebc-test.benwunet.com/api') {
				const vConsole = new VConsole();
			}
			// #endif
			console.log('onLaunch')
			const that = this
			// #ifdef H5
			// 获取访问链接进行解码url
			const href = decodeURIComponent(window.location.href)
			// 拆分href上的参数转换成对象
			const hrefObj = parseQueryStringt(href) // isApp bwlink benwu id
			let bw_link = {
				href: href, // url链接地址
				linkSource: href, // 原链接地址
				isApp: hrefObj.isApp || 0 // 是否是App
			}
			if (hrefObj.bwlink) {
				// 存在挂接关系对挂接参数进行解码
				const data = JSON.parse(utf8to16(base64decode(hrefObj.bwlink)))
				bw_link = {
					href: data.href || href, // url链接地址
					link: hrefObj.bwlink, // 挂接参数
					linkSource: hrefObj.bwlink, // 挂接参数来源
					sharerId: data.sharerId, // 分享者ID
					isApp: hrefObj.isApp || 0 // 是否是App打开
				}
			}
			if (hrefObj && hrefObj.isHead) {
				// 是否需要显示头部 1不显示头部
				bw_link.isHead = 1
			}
			const { bw_user_temp } = this.getBWData(['bw_user_temp'])
			if (bw_user_temp.memberId) {
				// 判断当前是否有登录用户，更新挂接关系参数
				const link = {
					sharerId: bw_user_temp.memberId
				}
				bw_link.link = base64encode(JSON.stringify(link))
				bw_link.sharerId = bw_user_temp.memberId
			}
			// link
			const get_bw_link = JSON.parse(uni.getStorageSync('bw_link') || '{}')
			// 在登录是重新刷新也页面之后登录来源失效，从缓存里面取出之前记录得登录来源写入
			if (get_bw_link.loginSource && href.includes('mine/mobile')) {
				bw_link.loginSource = get_bw_link.loginSource
			}
			// 存储挂接关系
			uni.setStorageSync('bw_link', JSON.stringify(bw_link))
			if (hrefObj.benwu) {
				// 跟APP规定传参统一 token=1&userId=1&statusBarHeight=1&isApp=1&companyId=1
				const benwu = utf8to16(base64decode(hrefObj.benwu))
				console.log('hrefObj.benwu', benwu)
				const {
					token,
					userId,
					statusBarHeight
				} = benwu.includes('&') || benwu.includes('=') ? parseQueryStringt(benwu) : benwu
				const params = {
					access_token: token,
					userId: userId,
					statusBarHeight: statusBarHeight, // 状态栏高度
					isApp: hrefObj.isApp || 0 // 是否是App打开
				}
				getApp().globalData.statusBarHeight = params.statusBarHeight
				console.log('hrefObj.benwu', params)
				uni.setStorageSync('bw_params', JSON.stringify(params));
			}

			// #endif
			// #ifdef H5
			uni.setStorageSync('url', window.location.href)
			// #endif
			this.getConfig()
		},
		userInfoCallback(data) {
			console.log(111111111111)
		},
		onShow: function() {
			console.log('App Show')
			this.getUser()
			this.getBWData(['bw_params', 'bw_user_temp', 'bw_card_temp', 'bw_company_info'])
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			// 根据token获取用户信息
			getUser() {
				const { bw_params, bw_link } = this.getBWData(['bw_params', 'bw_link'])
				let isBks = false
				// 是不是备考生路径，是备考生不去获取当前名片登录的用户信息，减少接口请求
				// #ifdef H5
				if(window.location.href.includes('#/bks/')){ isBks = true }
				// #endif
				if (bw_params.access_token && !isBks) {
					currentMember().then(res => {
						if (res.code == 0) {
							getApp().globalData.loginCount = 2
							uni.setStorageSync('bw_user_temp', JSON.stringify(res.data));
							const link = {
								sharerId: res.data.memberId
							}
							bw_link.link = decodeURIComponent(base64encode(JSON.stringify(link)))
							bw_link.sharerId = res.data.memberId
							uni.setStorageSync('bw_link', JSON.stringify(bw_link))
						}
					})
				}
			},
			// 获取系统配置信息
			getConfig() {
				const {bw_version, bw_config_color, bw_config} = this.getBWData(['bw_version', 'bw_config_color', 'bw_config'])
				// 请求当前版本
				moduleVersion().then(res=>{
					console.log('bw_config_color', bw_config_color)
					if(bw_version == res.data && (bw_config_color.globalColorType || bw_config.globalColor)){
						if(bw_config_color.globalColorType){
							this.colorConfig(bw_config_color)
						}else{
							this.colorConfig(bw_config.globalColor)
						}
					}else{
						uni.setStorageSync('bw_version', res.data);
						// #ifdef H5
						// 名片接口未更新3.5.4
						if(window.location.href.includes('#/bks/')){
							confAllColor({ requestSource: 1 }).then(res => {
								uni.setStorageSync('bw_config_color', JSON.stringify(res.data));
								this.colorConfig(res.data)
							})
						}else{
							confAll({ requestSource: 1 }).then(res => {
								uni.setStorageSync('bw_config', JSON.stringify(res.data));
								this.colorConfig(res.data.globalColor)
							})
						}
						// #endif
						// #ifdef MP
							confAll({ requestSource: 1 }).then(res => {
								uni.setStorageSync('bw_config', JSON.stringify(res.data));
								this.colorConfig(res.data.globalColor)
							})
						// #endif
					}
				}).catch(err=>{
					this.colorConfig(bw_config_color)
				})
			},
			// 配置颜色
			colorConfig(globalColor){
				let style = ''
				for (let i in globalColor) {
					if(globalColor[i] && globalColor[i].length == 9){
						style += `--${i}:${this.changeHexToRgba(globalColor[i])};`
					}else if(i == 'globalColorType'){
						this.globalData.appTheme = globalColor[i] == 2 ? 'lightBlue-theme' : 'night-theme'
					}else{
						style += `--${i}:${globalColor[i]};`
					}
				}
				// 灰度模式
				// if(res.data.blackWhiteFilter){
				// 	style += `filter: grayscale(100%);-webkit-filter: grayscale(100%);`
				// }
				// 通用样式配置
				globalColor.style = style
				this.globalData.globalColor = globalColor
				var pages = getCurrentPages() // 获取栈实例
				var page = pages[pages.length - 1] // 获取当前页面的数据，包含页面路由
				if (page && page.$vm && page.$vm.globalColor) {
					page.$vm.globalColor = globalColor
					if(page.$vm.theme != 'bks-theme'){
						page.$vm.theme = this.globalData.appTheme
					}
					console.log('darkViewBgColor', globalColor.darkViewBgColor)
					uni.setTabBarStyle({
						"color": globalColor.contentFontFourColor,
						"selectedColor": globalColor.senderViewColor,
						"borderStyle": globalColor.controllerBgColor,
						"backgroundColor": globalColor.darkViewBgColor,
					})
				}
			},
			changeHexToRgba (str, alpha = 1) {
			  const REGCOLOR = /^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/;
			  const ISRGBA = REGCOLOR.test(str);
			  if (ISRGBA === false) {
			    throw Error("颜色参数不合法");
			  }
			  const ISALPHA = typeof parseFloat(alpha) == "number" && parseFloat(alpha) <= 1 && parseFloat(alpha) >= 0
			  if (ISALPHA == false) {
			    throw Error("透明度参数不合法");
			  }
			  // 去掉#号  
			  const colorStr = str.slice(1);
			  const len = colorStr.length;
			  if (len === 3) {
			    const color = colorStr.split("").map(ele => parseInt(`0x${ele.repeat(2)}`)).join(",");
			    return `rgba(${color},${alpha})`;
			  }
			  const color = colorStr.match(/[A-z0-9]{2}/g).map(ele => parseInt(`0x${ele}`));
			  if (len === 6) {
			    return `rgba(${color.join(",")},${alpha})`;
			  }
			  if (len === 8) {
			    const opacity = (color.shift() / 255).toFixed(2);
			    return `rgba(${color.slice(0, 3).join(",")}, ${opacity})`;
			  }
			},
			// 获取统一存储的内容
			getBWData(type) {
				try {
					// token: bw_params, 用户信息: bw_user_temp, 名片信息: bw_card_temp, 公司信息: bw_company_info
					// link: bw_link, confAll: bw_config , 备考生:bw_bks_params，备考生学生信息： bw_bks_student， 备考生用户信息：bw_bks_user
					let BWData = {}
					type.filter(item=>{
						let value = uni.getStorageSync(item)
						if(typeof(value) != 'object'){
							value = JSON.parse(uni.getStorageSync(item) || '{}')
						}
						BWData[item] = value
						if(item == 'bw_user_temp'){ // 用户信息
							this.globalData.userTemp = value
						}else if(item == 'bw_card_temp'){// 名片信息
							this.globalData.cardTemp = value
						}else if(item == 'bw_company_info'){// 公司信息
							this.globalData.companyInfo = value
						}
					})
					console.log('BWData', BWData)
					return BWData
				} catch (e) {
					//TODO handle the exception
					console.log(e)
					return false
				}
			}
		}
	}
</script>

<style lang="scss">
	/*每个页面公共css */
	/* 引入字体图标 */
	@import "./static/css/font.css";
	@import "./static/css/font-bks.css";
	@import "./static/css/cue-theme.scss";
	@import "./static/css/base.css";
	@import url("@/static/css/weixin.scss");
</style>